<template>
  <div class="licence-issue-configure w-full h-full display-flex">
    <div class="left-select h-full">
      <a-select
        class="orup-select m-b-sm"
        v-model="selectOrup"
        placeholder="请选择"
        @change="handleSelectChange"
      >
        <a-select-option
          v-for="item in orupList"
          :key="item.id"
          :value="item.guid"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>
      <a-tree
        class="orup-tree"
        v-if="orupTreeList && orupTreeList.length > 0"
        checkable
        checkStrictly
        :show-icon="true"
        :default-expand-all="true"
        v-model="checkedKeys"
        :treeData="orupTreeList"
        :replaceFields="replaceFields"
        @check="handleTreeCheck"
      />
    </div>
    <div class="right-main h-full display-flex-column" style="overflow: hidden">
      <div class="w-full display-flex-column flex-1" style="overflow: hidden">
        <a-form-model
          class="w-full"
          style="padding-left: 10px"
          ref="orupForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          labelAlign="left"
        >
          <a-form-model-item label="组织机构编码">
            <a-input :disabled="!!form.organizationGuid" v-model="form.organizationGuid"/>
          </a-form-model-item>
          <a-form-model-item label="组织机构名称">
            <a-input :disabled="!!form.organizationName" v-model="form.organizationName"/>
          </a-form-model-item>
          <a-form-model-item label="发证机关名称" prop="issuingName">
            <a-input v-model="form.issuingName"/>
          </a-form-model-item>
          <a-form-model-item label="发证机关社会信用代码" prop="issuingUnifiedSocialCreditCode">
            <a-input v-model="form.issuingUnifiedSocialCreditCode"/>
          </a-form-model-item>
        </a-form-model>
        <div class="extend-box flex-1 display-flex-column" style="overflow: hidden">
          <div class="extend-title display-flex" style="justify-content: flex-start">
            <div class="extend-title-item">拓展机构:</div>
            <a-button class="extend-title-btn m-l-sm" type="primary" @click="handlerAddExtendOrg">新增</a-button>
          </div>
          <div class="extend-content w-full flex-1" style="overflow: auto">
            <div
              class="extend-content-item display-flex"
              style="justify-content: flex-start;margin-top: 10px"
              v-for="(item,index) in extendOrgList"
              :key="item.sortNum"
            >
              <div class="list-item m-r-sm">{{ `机构${index + 1}:` }}</div>
              <div class="list-item m-r-sm">
                <a-input v-model="item.issuingName" placeholder="请输入机构名称" style="width: 250px"/>
              </div>
              <div class="list-item m-r-sm">
                <a-input
                  v-model="item.issuingUnifiedSocialCreditCode"
                  placeholder="请输入机构代码"
                  style="width: 250px"/>
              </div>
              <a-button type="danger" @click="handlerDeleteExtendOrg(item)">删除</a-button>
            </div>
          </div>
        </div>
      </div>
      <div class="w-full display-flex" style="justify-content: flex-end">
        <a-button @click="saveForm" type="primary" class="m-r-xs">
          保存
        </a-button>
        <a-button @click="cancelForm" type="danger">
          取消
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
import orupService from '@/api/orupService'

export default {
  name: 'TreeAndTable',
  data () {
    return {
      selectOrup: undefined,
      orupList: [],
      orupTreeList: [],
      replaceFields: {
        children: 'children',
        title: 'fullName',
        key: 'guid'
      },
      checkedKeys: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      form: {
        organizationGuid: undefined,
        issuingName: undefined,
        organizationName: undefined,
        issuingUnifiedSocialCreditCode: undefined,
        organizationId: undefined
      },
      rules: {
        issuingName: [{
          required: true,
          message: '请输入发证机关名称',
          trigger: 'change'
        }],
        issuingUnifiedSocialCreditCode: [{
          required: true,
          message: '请输入发证机关社会信用代码',
          trigger: 'change'
        }]
      },
      prevForm: {},
      childItem: {},
      fatherItem: {},
      extendOrgList: []
    }
  },
  mounted () {
    this.init()
  },

  methods: {
    handlerDeleteExtendOrg (record) {
      const extendOrgList = []
      for (let i = 0; i < this.extendOrgList.length; i++) {
        const item = this.extendOrgList[i]
        if (item === record) {
          continue
        }
        extendOrgList.push(item)
      }
      this.extendOrgList = extendOrgList
    },
    handlerAddExtendOrg () {
      let maxSortNum = 0
      this.extendOrgList.forEach(item => {
        if (maxSortNum <= item.sortNum) {
          maxSortNum = item.sortNum + 1
        }
      })
      this.extendOrgList.push(
        {
          index: this.extendOrgList.length + 1,
          issuingUnifiedSocialCreditCode: undefined,
          issuingName: undefined,
          sortNum: maxSortNum
        }
      )
    },
    handleSelectChange (value) {
      this.orupTreeList = []
      this.checkedKeys = []
      this.getOrupTreeList(value)
    },
    async getOrupTreeList (value) {
      this.orupTreeList = await orupService.listAllOrgTree(value)
      this.orupTreeList = this.doFilterOrupTreeList(this.orupTreeList)
      this.checkedKeys.push(this.orupTreeList[0] && this.orupTreeList[0].guid)
      this.checkedKeys.length && this.getIssueMap(this.checkedKeys)
    },
    // 去除过滤挂起和撤销的机构
    doFilterOrupTreeList (arr) {
      // 结果数组
      const result = []

      const _this = this

      for (const item of arr) {
        // 如果当前节点的属性值与目标值匹配，则将其加入结果数组，并将其子节点设置为过滤后的子节点
        if (item.state === 1) {
          result.push({
            ...item,
            children: _this.doFilterOrupTreeList(item.children || [])
          })
        } else {
          // 如果当前节点没有匹配的属性值，检查其子节点，并将过滤后的子节点加入结果数组
          const filteredChildren = _this.doFilterOrupTreeList(item.children || [])
          if (filteredChildren.length > 0) {
            result.push({
              ...item,
              children: filteredChildren
            })
          }
        }
      }
      return result
    },
    handleTreeCheck (checkedKeys) {
      this.checkedKeys = [checkedKeys.checked.pop()]
      this.getIssueMap(this.checkedKeys)
    },
    getIssueMap (list) {
      this.form = {
        organizationGuid: undefined,
        issuingName: undefined,
        organizationName: undefined,
        issuingUnifiedSocialCreditCode: undefined,
        organizationId: undefined
      }
      this.prevForm = {}
      this.childItem = {}
      this.fatherItem = {}
      this.findItem(list[0], this.orupTreeList, 'child')
      this.form.organizationId = this.childItem.id
      this.form.organizationGuid = this.childItem.guid
      if (this.childItem.parentGuid) {
        this.findItem(this.childItem.parentGuid, this.orupTreeList, 'father')
        this.form.organizationName = this.fatherItem.fullName
      } else {
        this.form.organizationName = this.childItem.fullName
      }
      if (list[0]) {
        orupService.getIssuingOrganizationMap({ guid: list[0] }).then(res => {
          if (res) {
            this.form = res
          }
          this.prevForm = this._.cloneDeep(this.form)
        })
        orupService.getIssuingOrganizationExtendMap({ guid: list[0] }).then(res => {
          if (res) {
            this.extendOrgList = res
          }
        })
      }
    },
    findItem (guid, list, type) {
      for (const item of list) {
        if (item.guid === guid) {
          if (type === 'child') {
            this.childItem = item
          } else if (type === 'father') {
            this.fatherItem = item
          }
        }
        if (item.children.length > 0) {
          this.findItem(guid, item.children, type)
        }
      }
    },
    saveForm () {
      this.$refs.orupForm.validate(valid => {
        if (valid) {
          const extendOrgList = this.extendOrgList
          extendOrgList.forEach(item => {
            item.organizationId = this.form.organizationId
            item.organizationName = this.form.organizationName
            item.organizationGuid = this.form.organizationGuid
          })
          const promiseList = [
            orupService.saveIssuingOrganizationMap(this.form),
            orupService.saveIssuingOrganizationExtendMap({ guid: this.form.organizationGuid }, this.extendOrgList)
          ]
          Promise.all(promiseList).then(res => {
            if (res && res[0]) {
              this.form = res[0]
              this.extendOrgList = res[1]
              this.$message.success('更新成功！')
            }
          })
        }
      })
    },
    cancelForm () {
      this.form = this._.cloneDeep(this.prevForm)
    },
    async init () {
      // this.orupList = await orupService.getAllRealms()
      // 禅道id 92434 发证机关配置中的下拉框显示的域名要根据域管理员进行过滤。
      this.orupList = await orupService.listManagedRealmsOfUser(this.userInfo.id)
      this.selectOrup = this.orupList[0] && this.orupList[0].guid
      this.selectOrup && this.handleSelectChange(this.selectOrup)
    }
  }
}
</script>

<style lang="less" scoped>
.licence-issue-configure {
  padding: 20px;
  background: #fff;

  .left-select {
    width: 25%;

    .orup-select {
      width: 90%;
      height: 40px;
    }

    .orup-tree {
      width: 100%;
      height: calc(100% - 85px);
      overflow-y: auto;
      overflow-x: hidden;
    }
  }

  .right-main {
    width: 75%;
    flex-wrap: wrap;

    .btns {
      width: 80%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }

  .extend-box {
    padding-left: 10px;

    .extend-title {
      height: 35px;

      &-item {
        font-size: 18px;
        font-weight: bolder;
        line-height: 35px;
      }
    }

    .extend-content {
      margin-top: 10px;
    }
  }
}
</style>
